<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add()">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, i) in arr" :key="i">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="dele(i)">删除</button>
            <button @click="txt(i)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      id: 2,
      info: 0,
      name: null,
      age: null,
      gender: '',
      arr: [
        { id: 1, name: '李万博', age: 22, gender: '男' },
        { id: 2, name: '高姣姣', age: 21, gender: '女' },
      ],
    }
  },

  methods: {
    add() {
      if (this.info === 1) {
        console.log(this.id);
        this.arr.forEach((item) => {
          if (item.id === this.id) {
            item.id = this.id
            item.name = this.name
            item.age = this.age
            item.gender = this.gender
          }
        })
        return (this.info = 0)
      }
      if (this.name === '' || this.gender === '' || this.age === '') {
        return
      } else {
        this.id += 1
        this.arr.push({
          id: this.id,
          name: this.name,
          age: this.age,
          gender: this.gender,
        })
      }
    },
    dele(i) {
      this.arr.splice(i, 1)
    },
    txt(i) {
      this.info = 1
      this.id = this.arr[i].id
      this.name = this.arr[i].name
      this.age = this.arr[i].age
      this.gender = this.arr[i].gender
    },
  },
  computed: {},
}
</script>
